﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Windows;

using Caliburn.Micro;

using Haushaltsbuch.Domain.Users;
using Haushaltsbuch.Extensions;
using Haushaltsbuch.Helpers;

namespace Haushaltsbuch.ViewModels.Options
{
    //[Export(typeof(UserViewModel))]

    public class UserDetailViewModel : CslaScreen<UserEdit>
    {
        private readonly int id;
        public RoleEditList AllRoles { get; set; }
        public RoleEdit SelectedLeftRole { get; set; }
        public RoleEdit SelectedRightRole { get; set; }

        public UserDetailViewModel(int id)
        {
            this.id = id;
        }

        public void MoveToLeft()
        {
            if (this.SelectedRightRole == null)
                return;

            this.Model.Roles.Add(this.SelectedRightRole);
            this.AllRoles.Remove(this.SelectedRightRole);
        }

        public void MoveToRight()
        {
            if (this.SelectedLeftRole == null)
                return;
            this.AllRoles.Add(this.SelectedLeftRole);
            this.Model.Roles.Remove(this.SelectedLeftRole);
        }

        public override void CanClose(Action<bool> callback)
        {
            if (this.IsDirty)
            {
                var result = MessageBox.Show("Seite wirklich verlassen", "error", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    callback(false);
                    return;
                }
            }
            callback(true);
        }

        public void ChangePassword()
        {
            var windowManager = new WindowManager();
            dynamic settings = new ExpandoObject();
            settings.WindowStyle = WindowStyle.ToolWindow;
            settings.ShowInTaskbar = true;
            settings.Title = "This is a custom title";

            var changePasswordViewModel = new ChangePasswordViewModel();

            windowManager.ShowDialog(changePasswordViewModel, null, settings);

            if (!changePasswordViewModel.IsCanceled)
                this.Model.Password = PasswordHelper.GetHash(changePasswordViewModel.Password1);
        }

        public void Save()
        {
            Model.ApplyEdit();
            Model.Save();

        }

        protected override void OnInitialize()
        {
            this.Model = UserEdit.Get(this.id);
            this.AllRoles = RoleEditList.Get();
            foreach (var role in this.Model.Roles)
                this.AllRoles.Remove(this.AllRoles.Single(r => r.Id == role.Id));
        }
    }
}